package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.service.AdminProfilePasswordService;
import com.cskaoyan.market.service.AdminProfilePasswordServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/admin/profile/*")
public class AdminProfilePasswordController extends HttpServlet {
    AdminProfilePasswordService adminProfilePasswordService=new AdminProfilePasswordServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace("/admin/profile/", "");
        if ("password".equals(replace)){
            password(req,resp);
        }
    }

    private void password(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s = req.getReader().readLine();
        String s1 = JacksonUtil.parseString(s, "oldPassword");
        String s2 = JacksonUtil.parseString(s, "newPassword");
        String s3 = JacksonUtil.parseString(s, "newPassword2");

        if (StringUtils.isEmpty(s1)||StringUtils.isEmpty(s2)||StringUtils.isEmpty(s2)){
            Object fail = ResponseUtil.fail(400,"密码不能为空");
            String f = JacksonUtil.writeValueAsString(fail);
            resp.getWriter().println(f);
            return;
        }

        if (!StringUtils.isEmpty(s2)&&!s2.equals(s3)){
            Object fail2 = ResponseUtil.fail(400,"两次输入的密码不一致");
            String f2 = JacksonUtil.writeValueAsString(fail2);
            resp.getWriter().println(f2);
            return;
        }
        HttpSession session = req.getSession();
        MarketAdmin admin = (MarketAdmin) session.getAttribute("admin");

        if (!admin.getPassword().equals(s2)){
            Object fail2 = ResponseUtil.fail(400,"密码错误");
            String f2 = JacksonUtil.writeValueAsString(fail2);
            resp.getWriter().println(f2);
        }
        if(!adminProfilePasswordService.profilePassword(admin,s2)){
            Object fail3 = ResponseUtil.fail(400,"修改失败");
            String f3 = JacksonUtil.writeValueAsString(fail3);
            resp.getWriter().println(f3);
        }
        Object fail3 = ResponseUtil.ok();
        String f3 = JacksonUtil.writeValueAsString(fail3);
        resp.getWriter().println(f3);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
